package com.dd.census.controller;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import com.dd.census.controller.common.BaseController;
import com.dd.census.entity.Staff1;
import com.dd.census.service.Staff1Service;
import com.dd.census.tools.SysException;
import com.dd.census.tools.excel.ExcelExport;
import com.dd.census.tools.excel.ExcelExportCallback;
import com.dd.census.tools.validator.ValidateUtil.ValidationResult;
import com.dd.census.tools.validator.ValidateUtil;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFDataValidation;
import org.apache.poi.xssf.usermodel.XSSFDataValidationConstraint;
import org.apache.poi.xssf.usermodel.XSSFDataValidationHelper;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("rest/staff1")
public class Staff1Controller extends BaseController  {
	private static final Logger logger = LoggerFactory.getLogger(Staff1Controller.class);
	@Autowired
	private Staff1Service staff1Service;

	@RequestMapping("selectPage")
	public ResponseEntity<Object> select(@RequestBody Staff1 staff1, HttpServletRequest request) {
		try {
			return this.doSuccess(request, staff1Service.selectPage(staff1));

		} catch (SysException e) {
			// 业务异常
			return doFaild(request, e);

		} catch (Exception e) {
			// 系统异常
			logger.error("Internal Server Error", e);
			return doFaild(request, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

	@RequestMapping("selectAllIt")
	public ResponseEntity<Object> selectAllIt(@RequestBody Staff1 staff1, HttpServletRequest request) {
		try {
			return this.doSuccess(request, staff1Service.selectAllIt(staff1));

		} catch (SysException e) {
			// 业务异常
			return doFaild(request, e);

		} catch (Exception e) {
			// 系统异常
			logger.error("Internal Server Error", e);
			return doFaild(request, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

	@RequestMapping("insertStaff1")
	public ResponseEntity<Object> insertStaff1(HttpServletRequest request, @RequestBody Staff1 staff1) {

		try {
			// 基本输入验证
			ValidationResult rscheck = ValidateUtil.validate(staff1);
			if(!rscheck.isHasErrors()) {
				staff1.setCreateUserId(this.getUserId(request));
				staff1.setCreateTime(new Date());
				int amount = 0;
				if(staff1.getMethod() != null && staff1.getMethod() == 2){
					if(!staff1.getMonth01().equals("")){
						amount += Integer.parseInt(staff1.getMonth01());
					}if(!staff1.getMonth02().equals("")){
						amount += Integer.parseInt(staff1.getMonth02());
					}if(!staff1.getMonth03().equals("")){
						amount += Integer.parseInt(staff1.getMonth03());
					}
					staff1.setAmount(String.valueOf(amount));
				}
				staff1Service.insertStaff1(staff1);
				return this.doSuccess(request);
			}else {
				return this.doSuccess(request,rscheck);
			}
		} catch (Exception e) {
			// 系统异常
			logger.error("Internal Server Error", e);
			return doFaild(request, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

	@RequestMapping("/getById/{id}")
	public ResponseEntity<Object> getById(@PathVariable("id") String id, HttpServletRequest request) {
		try {
			return this.doSuccess(request, staff1Service.selectByKey(id));
		} catch (Exception e) {
			// 系统异常
			logger.error("Internal Server Error", e);
			return doFaild(request, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

	@RequestMapping("updateStaff1")
	public ResponseEntity<Object> updateStaff1(HttpServletRequest request, @RequestBody Staff1 staff1) {

		try {
			// 基本输入验证
			ValidationResult rscheck =ValidateUtil.validate(staff1);
			staff1.setUpdateUserId(this.getUserId(request));
			staff1.setUpdateTime(new Date());
			if(!rscheck.isHasErrors()) {
				int amount = 0;
                if(staff1.getMethod() != null && staff1.getMethod() == 2){
                	if(!staff1.getMonth01().equals("")){
						amount += Integer.parseInt(staff1.getMonth01());
					}if(!staff1.getMonth02().equals("")){
						amount += Integer.parseInt(staff1.getMonth02());
					}if(!staff1.getMonth03().equals("")){
						amount += Integer.parseInt(staff1.getMonth03());
					}
                	staff1.setAmount(String.valueOf(amount));
				}
				staff1Service.updateStaff1(staff1);
				return this.doSuccess(request);
			}else {
				return this.doSuccess(request,rscheck);
			}

		} catch (Exception e) {
			// 系统异常
			logger.error("Internal Server Error", e);
			return doFaild(request, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

	@RequestMapping("delete")
	public ResponseEntity<Object> delete(HttpServletRequest request, @RequestBody Staff1 staff1) {

		try {
			staff1Service.delete(staff1);

			return this.doSuccess(request);
		} catch (Exception e) {
			// 系统异常
			logger.error("Internal Server Error", e);
			return doFaild(request, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

	@RequestMapping("exportMember")
	public void exportMember(HttpServletRequest request, HttpServletResponse response, String name, String mobile, String landerName) {

		Staff1 member = new Staff1();
		member.setName(name);
		member.setTel(mobile);
		member.setLanderName(landerName);
		List<Staff1> list = staff1Service.selectList(member);
		try {
			response.setCharacterEncoding("UTF-8");
			response.setHeader("content-Type", "application/vnd.ms-excel");
			String filedisplay ="会员.xls";
			Integer[] arr = {};
			//防止文件名含有中文乱码
			response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(filedisplay, "utf-8"));
			response.setHeader("FileName", URLEncoder.encode(filedisplay, "utf-8"));
			response.setHeader("Access-Control-Expose-Headers", "FileName");
			OutputStream out = response.getOutputStream();

			new ExcelExport().createExcel(out, arr, list, Staff1.class, "sheet1", new ExcelExportCallback() {

				@Override
				public void call(Sheet sheet) {
					// 下拉数据
					String[] strs = new String[] { "name-20[^111^]", "name-25[^222^]" };
					XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper((XSSFSheet) sheet);
					XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint) dvHelper.createExplicitListConstraint(strs);
					// 显示位置(起始行/结束行/起始列/结束列)
					CellRangeAddressList addressList = new CellRangeAddressList(1, 65535, 0, 1);
					XSSFDataValidation validation = (XSSFDataValidation) dvHelper.createValidation(dvConstraint, addressList);
					// 错误提示
					validation.setShowErrorBox(true);
					// 添加
					sheet.addValidationData(validation);
				}
			});
		} catch (Exception e) {
			System.err.println(e);
			e.printStackTrace();
		}
	}
}